package com.tiheima.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.tiheima.utils.JwtUtils;
import com.tiheima.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author byZhao
 * @create 2025/5/22 16:11
 * @description
 *  登录的拦截器
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 从请求头中获取令牌 token
        String token = request.getHeader("token");
        if (ObjectUtil.isNull(token)){
            // 响应错误信息
            // HttpStatus.UNAUTHORIZED.value() 是 401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        // 验证令牌
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object o = claims.get("id");
            ThreadLocalUtil.set((Integer) o);
        }catch (Exception e){
            log.error("解析令牌失败，失败的原因：{}",e.getMessage());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 防止内存泄露
        ThreadLocalUtil.remove();
    }
}
